<template>
    <div id="detailAll">
        <div id="leftDetail">
            <h3 style="margin: 20px;"></h3>
            <el-form v-model="labelPosition" label-width="70px" :model="addPeopleForm" size="mini">
                <el-form-item label="客户ID">
                    <el-input v-model="addPeopleForm.kehu_id"></el-input>
                </el-form-item>
                <el-form-item label="客户名称">
                    <el-input v-model="addPeopleForm.kehu_name"></el-input>
                </el-form-item>
                <el-form-item label="联系人">
                    <el-input v-model="addPeopleForm.contact"></el-input>
                </el-form-item>
                <el-form-item label="电话">
                    <el-input v-model="addPeopleForm.tel"></el-input>
                </el-form-item>
                <el-form-item label="邮箱">
                    <el-input v-model="addPeopleForm.email"></el-input>
                </el-form-item>
                <el-form-item label="账号">
                    <el-input v-model="addPeopleForm.account.username"></el-input>
                </el-form-item>
                <p>投票建议订阅数 <span style="float: right; color:#67C23A;">{{ addPeopleForm.vote_num }}</span></p>
                <p>治理风险研究订阅数 <span style="float: right; color: #E6A23C;">{{ addPeopleForm. study_num}}</span></p>

                <el-form-item label="">
                    <el-button type="success" plain size="mini" @click="showSetPasswordDialog">修改密码</el-button>
                    <el-button type="primary" plain size="mini" @click="addCustomer">提交</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div id="rightDetail">
            <div class="tabs">
                <el-tabs v-model="activeName" @tab-click="handleClick">
                    <el-tab-pane label="投票建议" name="first">
                        <CustomerAside v-if="!dataFlag" flag="1"  @orderChangeChild="orderChange" />
                    </el-tab-pane>
                    <el-tab-pane label="治理风险研究" name="second">
                        <CustomerAside v-if="dataFlag" flag="2"  @orderChangeChild="orderChange" />
                    </el-tab-pane>
                </el-tabs>
            </div>
        </div>
        <el-dialog title="设置密码" 
        :visible.sync="dialogTableVisible" 
        :close-on-click-modal="false"
        width="30%">
            <el-form :model="ruleForm2" status-icon :rules="rules2" ref="ruleForm2" label-width="100px" class="demo-ruleForm">
                <el-form-item label="新密码" prop="pass">
                    <el-input size="mini" type="password" v-model="ruleForm2.pass" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="checkPass">
                    <el-input size="mini" type="password"  v-model="ruleForm2.checkPass" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
             <span slot="footer" class="dialog-footer">
                <el-button type="primary" size="mini" @click="setPassWord('ruleForm2')">提 交</el-button>
                <el-button size="mini"  @click="dialogTableVisible = false">取 消</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import CustomerAside from './customerAside';
export default {
    name: 'customerDetail',
    data(){
        var validatePass = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请输入密码'));
            } else {
            if (this.ruleForm2.checkPass !== '') {
                this.$refs.ruleForm2.validateField('checkPass');
            }
            callback();
            }
        };
        var validatePass2 = (rule, value, callback) => {
            if (value === '') {
            callback(new Error('请再次输入密码'));
            } else if (value !== this.ruleForm2.pass) {
            callback(new Error('两次输入密码不一致!'));
            } else {
            callback();
            }
        };
        return {
            dialogTableVisible: false,
            labelPosition: 'right',
            addPeopleForm: {
                id:'',
                kehu_id: '',
                kehu_name: '',
                contact: '',
                tel: '',
                email: '',
                account: {
                    id:'',
                    username: ''
                },
                study_num: 0,
                vote_num:0
            },
            ruleForm2:{
                pass:'',
                checkPass:''
            },
            rules2: {
                pass: [
                    { validator: validatePass, trigger: 'blur' }
                ],
                checkPass: [
                    { validator: validatePass2, trigger: 'blur' }
                ]
            },
            activeName: 'first',
            dataFlag: false,
        }
    },
    mounted () {
        this.addPeopleForm.id = this.$route.query.id;

        if (!this.addPeopleForm.id) {
            console.log('添加客户进来的')
        }else{
            this.$axios.get(`/api/kehu/${this.$route.query.id}/`).then(res => {
                if (res.status === 200 && res.data.account) {
                    this.addPeopleForm = res.data;
                }else{
                    res.data.account = {username: ''};
                    this.addPeopleForm = res.data;
                }
            })
        }
    },
    methods: {
        orderChange(data){
            console.log(data);
            if (!this.addPeopleForm.id) {
            console.log('添加客户进来的')
        }else{
            this.$axios.get(`/api/kehu/${this.$route.query.id}/`).then(res => {
                if (res.status === 200 && res.data.account) {
                    this.addPeopleForm = res.data;
                }else{
                    res.data.account = {username: ''};
                    this.addPeopleForm = res.data;
                }
            })
        }

        },
        addCustomer () {
            let infoError = false;
            for(let k in this.addPeopleForm){
                if(k==='id'|| k === 'contact' || k === 'account' || k === 'study_num' || k==='vote_num'){
                    console.log(k);
                    continue;
                }else{
                    console.log(this.addPeopleForm[k]);

                    if(!this.addPeopleForm[k]){
                        this.$message({
                            message: '除联系人外，其他信息必填！',
                            type: 'error'
                        })
                        infoError = true;
                        break;
                    }
                }

            }

            if(infoError){
                return false;
            }

            if(this.addPeopleForm.account.username !== '' && !infoError){
                if(this.addPeopleForm.id){
                    this.$axios.put(`/api/kehu/${this.addPeopleForm.id}/`,{...this.addPeopleForm}).then(res => {
                        this.$message({
                                message: '修改成功',
                                type: 'success'
                            })

                    }).catch(error=>{
                        console.log(error)
                        if(error.status === 400 ){
                                if(error.data.account && error.data.account.username){
                                    this.$message({
                                    message: '修改失败，用户名已存在',
                                    type: 'error'
                                })
                            }
                        }
                    })
                }else{
                    
                    this.$axios.post('/api/kehu/',{...this.addPeopleForm}).then(res => {
                        if (res.status === 201 && res.data.account.id) {
                            this.$router.push({
                                path: '/customerManage'
                            });
                        }else{
                            this.$message({
                                message: '创建账户失败',
                                type: 'error'
                            })
                        }
                    }).catch(error=>{
                        console.log(error)
                        if(error.status === 400 ){
                            if(error.data.account && error.data.account.username){
                                this.$message({
                                message: '添加账户失败，用户名已存在',
                                type: 'error'
                                })

                            }else{
                                let message = '';
                                for(let k in error.data){
                                    message += error.data[k]
                                }
                                this.$message({
                                message: '添加账户失败，'+ message,
                                type: 'error'
                                })
                            }
                        }
                    })
                }
                // this.$router.go(0)
            }else{
                this.$message({
                    message:'请录入用户账号',
                    type:'info'
                })
            }
        },
        handleClick(tab, event) {
            let id = event.target.id;
            if (id == 'tab-first') {
                this.dataFlag = false;
            }else if (id == 'tab-second') {
                this.dataFlag = true;
            }
        },
        showSetPasswordDialog(){
            if(this.addPeopleForm.account.id){
                this.dialogTableVisible = true;
                this.$nextTick(function(){
                    this.$refs.ruleForm2.resetFields();
                })
            }else{
                this.$message({
                    type: 'info',
                    message: '请先设置用户账号，然后再为用户设置密码'
                });
            }
        },
        setPassWord(formName){
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.$axios.post(`api/kehu/${this.addPeopleForm.id}/change_password/`,
                        JSON.stringify({password: this.ruleForm2.pass})
                    )
                    .then((res)=>{
                        if (res.status === 200) {
                            this.dialogTableVisible = false;
                            this.$message({
                                message:'密码修改成功',
                                type:'success'
                            })
                        }
                    })
                } else {
                    this.$message({
                        message:'密码修改失败',
                        type:'error'
                    })
                    console.log('error submit!!');
                    return false;
                }
            });
            
        }
    },
    components: {
        CustomerAside
    }
}
</script>
<style lang="scss" scoped>
#detailAll {
    display: flex;
}
#leftDetail {
    padding-right: 10px;
    border-right: 1px solid #cccccc;
}
#rightDetail {
    flex: 1;
    min-width: 700px;
}
.tabs{
    margin: 20px 0 0 20px;
}
</style>

